package com.xh.petdogexpert.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ValudateView<T, D> {

	ListHashMap errorMsg = null;

	public void init() {
		errorMsg = new ListHashMap();
	}

	public ListHashMap getErrorMsg() {
		return errorMsg;
	}

	protected void notNull(Field<T, D> field) {
		if (field.value == null) {
			errorMsg.put(field.name, field.name + " 不能为空");
		}
	};

	protected void notEmpty(Field<T, D> field) {
		if (field.value == "") {
			errorMsg.put(field.name, field.name + " 不能为空");
		}
	};

	public static class Field<T, D> {
		T name;
		D value;

		public Field(T name, D value) {
			super();
			this.name = name;
			this.value = value;
		}

		public T getName() {
			return name;
		}

		public Object getValue() {
			return value;
		}
	}

	/*
	 * 可以放置多个错误信息的map
	 */
	class ListHashMap extends HashMap<T, List<String>> {

		private static final long serialVersionUID = 1L;

		public ListHashMap() {
			super();
		}

		public void put(T key, String value) {
			List<String> val = super.get(key);
			if (val == null)
				val = new ArrayList<String>();
			val.add(value);
			super.put(key, val);
		}
	}

	public interface ValudateMethod {
		String valudate(Object data);
	}

	// 在自定义校验方法的基础上增加 1.校验失败 2.添加到错误信息里面
	public String valudate(Field<T, D> field, ValudateMethod method) {
		String msg = null;

		try {
			msg = method.valudate(field.getValue());
		} catch (Exception e) {
			e.printStackTrace();
			errorMsg.put(field.name, field.name + "校验失败");
		}

		if (msg != null)
			errorMsg.put(field.name, msg);

		return msg;
	}

	// 抛出异常
	public void throwError() throws BaseException {
		if (!errorMsg.isEmpty())
			throw new BaseException(errorMsg, BaseException.FORM_VALUDATE);
	}
}
